package com.huang.educenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.huang.educenter.entity.UcenterMember;
import com.huang.educenter.service.UcenterMemberService;
import com.huang.educenter.utils.ConstantWxUtils;
import com.huang.educenter.utils.HttpClientUtils;
import com.huang.servicebase.execptionhandler.huangException;
import com.hunag.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService service;

    @GetMapping("loginwx")
    public String getWXcode() throws UnsupportedEncodingException {
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //对redirect_url编码
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");

        //传值
        String url = String.format(baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "hjw");

        return "redirect:" + url;
    }

    //获取扫码人信息
    @GetMapping("callback")
    public String callback(String code, String statu) {
        try {
            //获取code  临时票据 类似验证码

//拿着code  请求微信固定地址  拿到 access_token 和openid
            String baseAccessTokenUrl =
                    "https://api.weixin.qq.com/sns/oauth2/access_token" +
                            "?appid=%s" +
                            "&secret=%s" +
                            "&code=%s" +
                            "&grant_type=authorization_code";
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code);
            //使用httpclient  直接 返回访问地址后的返回数据     工具类
            String tokenInfo = HttpClientUtils.get(accessTokenUrl);
            //拿出 access_token and  openid
            Gson gson = new Gson();
            Map map = gson.fromJson(tokenInfo, Map.class);
            String accessToken = (String) map.get("access_token");
            String openid = (String) map.get("openid");

//查是否 数据库有没有这个扫码人
            QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
            wrapper.eq("openid", openid);
            UcenterMember one = service.getOne(wrapper);
            if (one == null) {

                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
                //拿到凭证  访问地址获取扫码人的信息
                String userInfo = HttpClientUtils.get(userInfoUrl);
                Map userMap = gson.fromJson(userInfo, Map.class);
                String nickname = (String) userMap.get("nikename");
                String headimgurl = (String) userMap.get("headimgurl");
                //向数据库中插入一条记录
                UcenterMember member = new UcenterMember();
                member.setNickname(nickname);
                member.setOpenid(openid);
                member.setAvatar(headimgurl);
                service.save(member);

            }
            String jwtToken = JwtUtils.getJwtToken(one.getId(), one.getNickname());
            System.out.println(jwtToken);
            return "redirect:http://localhost:3000?token=" + jwtToken;

        } catch (Exception e) {
            throw new huangException(20001, "登陆失败");
        }


    }
}
